package com.jzo2o.foundations.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.expcetions.CommonException;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.foundations.enums.FoundationStatusEnum;
import com.jzo2o.foundations.mapper.RegionMapper;
import com.jzo2o.foundations.mapper.ServeItemMapper;
import com.jzo2o.foundations.mapper.ServeMapper;
import com.jzo2o.foundations.mapper.ServeSyncMapper;
import com.jzo2o.foundations.model.domain.*;
import com.jzo2o.foundations.model.dto.request.ServePageQueryReqDTO;
import com.jzo2o.foundations.model.dto.request.ServeUpsertReqDTO;
import com.jzo2o.foundations.model.dto.response.ServeResDTO;
import com.jzo2o.foundations.model.dto.response.ServeTypeResDTO;
import com.jzo2o.foundations.service.IServeService;
import com.jzo2o.mysql.utils.PageHelperUtils;
import com.jzo2o.mysql.utils.PageUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.FormatterClosedException;
import java.util.List;

/**
 * @author 郑海飞
 * @version 1.0
 * @description:
 * @date 2024/6/3 20:05
 */
@Service
public class ServeServiceImpl extends ServiceImpl<ServeMapper, Serve> implements IServeService {
    @Resource
    ServeItemMapper serveItemMapper;
    @Resource
    RegionMapper regionMapper;

    @Resource
    ServeSyncMapper serveSyncMapper;
    /**
     * @Author 郑海飞
     * @Description //根据区域id查询列表分页
     * @Date 20:09 2024/6/3
     * @Param
     * @param servePageQueryReqDTO
     * @return com.jzo2o.common.model.PageResult<com.jzo2o.foundations.model.dto.response.ServeResDTO>
     */

    @Override
    public PageResult<ServeResDTO> page(ServePageQueryReqDTO servePageQueryReqDTO) {

        PageResult<ServeResDTO> serveResDTOPageResult = PageHelperUtils.selectPage(servePageQueryReqDTO, () -> baseMapper.queryServeListByRegionId(servePageQueryReqDTO.getRegionId()));

        return serveResDTOPageResult;
    }

    /**
     * @Author 郑海飞
     * @Description //添加区域服务
     * @Date 20:26 2024/6/3
     * @Param
     * @param serveUpsertReqDTOList
     *
     */

    @Override
    @Transactional
    public void batchAdd(List<ServeUpsertReqDTO> serveUpsertReqDTOList) {
        serveUpsertReqDTOList.stream().forEach(serveResDTO -> {
            //1.校验服务项是否为启用状态,不是启用状态不能新增
            ServeItem serveItem = serveItemMapper.selectById(serveResDTO.getServeItemId());
            if(serveItem==null||serveItem.getActiveStatus()!= FoundationStatusEnum.ENABLE.getStatus()){
                throw new ForbiddenOperationException("该服务未启用无法添加到区域下使用");
            }
            //2.校验是否重复新增
            Integer count = lambdaQuery()
                    .eq(Serve::getRegionId, serveResDTO.getRegionId())
                    .eq(Serve::getServeItemId, serveResDTO.getServeItemId())
                    .count();
            if(count>0){
                throw new ForbiddenOperationException(serveItem.getName()+"服务已存在");
            }
            //3.新增服务
            Serve serve = BeanUtil.toBean(serveResDTO, Serve.class);
            //3.1查询区域对象
            Region region = regionMapper.selectById(serveResDTO.getRegionId());
            //3.2区域服务设置城市编码
            serve.setCityCode(region.getCityCode());
            baseMapper.insert(serve);
        });
    }

    /**
     * @Author 郑海飞
     * @Description //区域服务价格修改
     * @Date 21:13 2024/6/3
     * @Param
     * @param id
     * @param price
     *
     */
    @Override
    public Serve  update(Long id, BigDecimal price) {
        //1.更新服务价格
        boolean update = lambdaUpdate()
                .eq(Serve::getId, id)
                .set(Serve::getPrice, price)
                .update();
        if(!update){
            throw new ForbiddenOperationException("区域服务价格修改失败");
        }
        return baseMapper.selectById(id);
    }

    /**
     * @Author 郑海飞
     * @Description //区域服务上架
     * @Date 21:17 2024/6/3
     * @Param
     * @param id
     *
     */
    @Override
    public Serve onSale(Long id) {
        Serve serve = baseMapper.selectById(id);
        if(ObjectUtil.isNull(serve)){
            throw new ForbiddenOperationException("区域服务不存在");
        }
        //上架状态
        Integer saleStatus = serve.getSaleStatus();
        //草稿或下架状态才能上架
        if(!(saleStatus==FoundationStatusEnum.INIT.getStatus()||saleStatus==FoundationStatusEnum.DISABLE.getStatus())){
            throw new ForbiddenOperationException("草稿或下架状态才能上架");
        }
        //服务项id
        Long serveItemId = serve.getServeItemId();
        ServeItem serveItem = serveItemMapper.selectById(serveItemId);
        if(ObjectUtil.isNull(serveItem)){
            throw new ForbiddenOperationException("所属服务项不存在");
        }
        //服务项的启用状态
        Integer activeStatus = serveItem.getActiveStatus();
        //服务项为启用状态即可上架
        if(!(activeStatus==FoundationStatusEnum.ENABLE.getStatus())){
            throw new ForbiddenOperationException("服务项为启用状态即可上架");
        }
        //更新上架状态
        boolean update = lambdaUpdate()
                .eq(Serve::getId, id)
                .set(Serve::getSaleStatus, FoundationStatusEnum.ENABLE.getStatus())
                .update();
        if(!update){
            throw new CommonException("启动服务失败");
        }
        //返回统一对象
        return baseMapper.selectById(id);
    }

    /**
     * @Author 郑海飞
     * @Description //区域服务删除
     * @Date 21:37 2024/6/3
     * @Param
     * @param id
     *
     */
    @Override
    public void deleteById(Long id) {
        Serve serve = baseMapper.selectById(id);
        if(ObjectUtil.isNull(serve)){
            throw new ForbiddenOperationException("区域服务不存在");
        }
        //草稿状态才能删除
        if(!(serve.getSaleStatus()==FoundationStatusEnum.INIT.getStatus())){
            throw new ForbiddenOperationException("草稿状态才能删除");
        }
        //删除区域服务
        baseMapper.deleteById(id);
        //同步数据
        serveItemMapper.deleteById(id);
    }

    /**
     * @Author 郑海飞
     * @Description //区域服务下架
     * @Date 21:41 2024/6/3
     * @Param
     * @param id
     *
     */
    @Override
    public Serve offSale(Long id) {
        Serve serve = baseMapper.selectById(id);
        if(ObjectUtil.isNull(serve)){
            throw new ForbiddenOperationException("区域服务不存在");
        }
        //上架状态
        Integer saleStatus = serve.getSaleStatus();
        //上架状态即可下架
        if(!(saleStatus==FoundationStatusEnum.ENABLE.getStatus())){
            throw new ForbiddenOperationException("上架状态即可下架");
        }
        //更新下架状态
        LambdaUpdateWrapper<Serve> updateWrapper = Wrappers.<Serve>lambdaUpdate()
                .eq(Serve::getId, id)
                .set(Serve::getSaleStatus, FoundationStatusEnum.DISABLE.getStatus());
        update(updateWrapper);
        //删除同步表的数据
        serveItemMapper.deleteById(id);
        return  baseMapper.selectById(id);
    }

    /**
     * @Author 郑海飞
     * @Description //设置热门
     * @Date 21:46 2024/6/3
     * @Param
     * @param id
     *
     */
    @Override
    @Transactional
    public void changeHotStatus(Long id, int flag) {
        //设置热门
        LambdaUpdateWrapper<Serve> wrapper = Wrappers.<Serve>lambdaUpdate()
                .eq(Serve::getId, id)
                .set(Serve::getIsHot, flag)
                .set(Serve::getHotTimeStamp, System.currentTimeMillis());
        super.update(wrapper);
        //同步数据
        ServeSync serveSync = new ServeSync();
        serveSync.setId(id);
        serveSync.setIsHot(flag);
        serveSync.setHotTimeStamp(System.currentTimeMillis());
        serveSyncMapper.updateById(serveSync);
    }
}
